package com.test.web.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.test.web.dao.UserDao;
import com.test.web.pojo.User;

public class UserDaoImpl implements UserDao {

	@Override
	public List<User> all() {
		List<User> users = new ArrayList<>();
		
		User user = new User();
		user.setName("Zack");
		user.setAge(20);
		user.setAddress("Nanjing");
		
		users.add(user);
		
		user = new User();
		user.setName("Zoe");
		user.setAge(60);
		user.setAddress("Beijing");
		
		users.add(user);
		
		return users;
	}

	@Override
	public List<User> allByDM() {
		List<User> users = new ArrayList<>();
		
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test" , "root" , "root");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (null != connection) {
			ResultSet result = null;
			
			try {
				Statement statement = connection.createStatement();
				result = statement.executeQuery("select * from user");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (null != result) {
				try {
					User user = null;
					while(result.next()) {
						user = new User();
						user.setName(result.getString("name"));
						user.setAge(result.getInt("age"));
						user.setAddress(result.getString("address"));
						users.add(user);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return users;
	}

	@Override
	public List<User> allByJNDI() {
		List<User> users = new ArrayList<>();
		Connection connection = null;
		
		try {
			Context context = new InitialContext();
			DataSource datasource = (DataSource)context.lookup("java:comp/env/jdbc/web");
			connection = datasource.getConnection();
		} catch (NamingException | SQLException e) {
			e.printStackTrace();
		}
		
		if (null != connection) {
			ResultSet result = null;
			
			try {
				Statement statement = connection.createStatement();
				result = statement.executeQuery("select * from user");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (null != result) {
				try {
					User user = null;
					while(result.next()) {
						user = new User();
						user.setName(result.getString("name"));
						user.setAge(result.getInt("age"));
						user.setAddress(result.getString("address"));
						users.add(user);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return users;
	}
}
